<script lang="ts" setup>
import { useVbenDrawer, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Card,
  message,
  Popconfirm,
  Select,
  SelectOption,
  Space,
  TabPane,
  Tabs,
  Tooltip,
} from 'ant-design-vue';
import Draggable from 'vuedraggable';

import { useVbenForm } from '#/adapter/form';
import { getSettingLang } from '#/api/admin/setting';
import {
  deleteThemesFileBlockWidget,
  getThemesFileSetting,
} from '#/api/admin/theme';
import Icon from '#/components/Icons';
import { useThemeStore } from '#/store';
import { formatValues, generateFormSchema } from '#/utils';

import FileWidgetsConfigModalView from './FileWidgetsConfigModal.vue';
import FileWidgetsModalView from './FileWidgetsModal.vue';

const state: any = reactive({
  data: {},
  activeKey: '',
  has_config: false,
  has_public_config: false,
  has_widget: false,
  enabled: true,
  dragging: false,
  widgets_blocks: [],
  admin_content_lang: 'zh-cn',
  adminContentLangList: ['zh-cn'],
  theme: '',
  file: '',
  file_id: '',
});
const themeFiles = ref<any>();
const { setThemeInfo, $reset } = useThemeStore();

/** 文件设置表单 */
const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  showDefaultActions: false,
  // 提交函数
  handleSubmit: async (values) => {
    const formApiState = formApi.getState();
    const formApiStateSchema = formApiState?.schema || [];
    const newValues = formatValues(formApiStateSchema, values);
    const files = {
      [state.data.file_id]: { vars: newValues },
    };
    useThemeStore().onPostThemesFileSetting(files);
  },
});

/** 获取模板配置 */
const onThemesFileSetting = async () => {
  const { data } = await getThemesFileSetting(state.theme, state.file);
   const data_1 =formDrawerApi.getData();
   data_1.file = state.file;
   formDrawerApi.setData(data_1);
  if (data.file?.more?.widgets_blocks) {
    // 转换函数
    const transformWidgetsToArray = (data: any): any => {
      const transformed = {
        widgets_blocks: Object.fromEntries(
          Object.entries(data).map(([blockKey, blockValue]: any) => {
            // 确保顺序，使用 Object.keys 保持顺序
            const widgetsArray = Object.keys(blockValue.widgets).map((key) => ({
              id: key,
              ...blockValue.widgets[key],
            }));

            return [
              blockKey,
              {
                ...blockValue,
                widgets: widgetsArray,
              },
            ];
          }),
        ),
      };

      return transformed.widgets_blocks;
    };

    const result = transformWidgetsToArray(data.file.more.widgets_blocks);
    data.file.more.widgets_blocks = result;
  }
  state.file_id = data.file_id;
  state.data = data;
  // 筛选出 is_public=1 的对象
  const publicItems = data.files.filter((item: any) => item.is_public === 1);
  const publicItem = publicItems ? publicItems[0] : null;

  state.has_config = data.file?.more?.vars;
  state.has_public_config = data.file?.is_public !== 1 && publicItem;
  state.has_widget = data.file?.more?.widgets_blocks;

  if (state.has_widget) {
    state.activeKey = '1';
  } else if (state.has_config) {
    state.activeKey = '2';
  } else if (state.has_public_config) {
    state.activeKey = '3';
  }
  if (data.file?.more?.vars || publicItem) {
    try {
      const config = publicItem.more.vars;

      const { schema, values } = generateFormSchema(config);

      formApi.setState({ schema });
      formApi.setValues(values);
    } catch (error) {
      console.error('加载配置失败', error);
      message.error('加载配置失败，请重试');
    }
  }
};

/** 抽屉初始化 */
const [Drawer, formDrawerApi] = useVbenDrawer({
  async onConfirm() {
    if (state.activeKey === '2') {
      await formApi.validateAndSubmitForm();
    }
    formDrawerApi.close();
  },
  async onOpenChange(isOpen: boolean) {
 
    // 进来先清空数据
    $reset();
    if (isOpen) {
      const {
        data: { lang_setting },
      } = await getSettingLang();
      state.admin_content_lang = lang_setting.default_lang;
      state.adminContentLangList = lang_setting.allow_lang_list;
      const values: any = formDrawerApi.getData();
    
      formDrawerApi.setState({
        title: `${values.theme}--模板文件配置`,
 
      });

      const file =values.file!==''?values.file:( values.files.length > 0 ? values.files[0].file : '');

      themeFiles.value = values.files;
      state.theme = values.theme;
      state.file = file;
      onThemesFileSetting();
      setThemeInfo({
        theme: values.theme,
        file,
        admin_content_lang: state.admin_content_lang,
      });
    }
  },
});

/** 表单提交转换格式 */
const transformData = (input: any, fileId: string): any => {
  const result: any = {
    [`file${fileId}`]: {},
  };

  Object.keys(input).forEach((section) => {
    if (input[section] && input[section].widgets) {
      result[`file${fileId}`][section] = input[section]?.widgets?.map(
        (widget: any, index: any) => ({
          index,
          file_id: fileId,
          widget_id: widget.id,
        }),
      );
    }
  });

  return result;
};
/** 组件推拽结束执行排序 */
const onDragEnd = async () => {
  state.dragging = false;
  const data = transformData(
    state.data.file.more.widgets_blocks,
    state.data.file_id,
  );
  useThemeStore().onPostThemesWidgetSort(data);
};

/** 删除组件的控件 */
const handleDelete = async (row: any, key: any) => {
  const { msg } = await deleteThemesFileBlockWidget({
    block_name: key,
    file: state.data.file_id,
    theme: state.theme,
    widget_id: row.id,
    admin_content_lang: state.admin_content_lang,
  });
  message.success(msg);
  await onThemesFileSetting();
};

/** 设置控件列表弹窗 */
const [FileWidgetsModal, FileWidgetsApi] = useVbenModal({
  connectedComponent: FileWidgetsModalView,
  async onClosed() {
    await onThemesFileSetting();
  },
});
/** 打开新增控件列表弹窗 */
const openDialog = (blockName: number | string) => {
  FileWidgetsApi.setData({
    file: state.file,
    theme: state.theme,
    block_name: blockName,
  });
  FileWidgetsApi.open();
};

/** 设置自由控件设置窗口 */
const [FileWidgetsConfigModal, FileWidgetsConfigModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FileWidgetsConfigModalView,
  async onClosed() {
    await onThemesFileSetting();
  },
});

/** 打开自由控件设置弹窗 */
const openWidgetsSettingModal = (blockName: any, widget: any) => {
  setThemeInfo({
    block_name: blockName,
    file_id: state.file_id,
    widget_id: widget.id,
  });
  FileWidgetsConfigModalApi.setState({
    title: `${widget.title}设置`,
  });
  FileWidgetsConfigModalApi.setData({
    blockName,
    widget,
    file_id: state.file_id,
  });
  FileWidgetsConfigModalApi.open();
};

// 选择语言后设置状态
const onChangeLang = (value: any) => {
  setThemeInfo({ admin_content_lang: value });
};
</script>
<template>
  <Drawer>
    <FileWidgetsModal />
    <FileWidgetsConfigModal />
    <Card>
      <Space>
        <Select
          v-model:value="state.file"
          :field-names="{
            label: 'name',
            value: 'file',
          }"
          :options="themeFiles"
          style="width: 220px"
          @select="onThemesFileSetting()"
        />
        <Select
          v-model:value="state.admin_content_lang"
          style="width: 120px"
          @select="onChangeLang"
        >
          <SelectOption
            v-for="lang in state.adminContentLangList"
            :key="lang.lang"
            :value="lang.lang"
          >
            {{ lang.lang }}
          </SelectOption>
        </Select>
      </Space>
    </Card>
    <Tabs v-model:active-key="state.activeKey">
      <TabPane v-if="state.has_widget" key="1" tab="组件">
        <Card
          v-for="(widget, key) in state.data.file.more.widgets_blocks"
          :key="key"
          :bordered="false"
          :title="widget.title"
          class="mb-2"
        >
          <template #extra>
            <Tooltip title="添加组件">
              <Button type="link" @click="openDialog(key)">
                <template #icon>
                  <span class="anticon">
                    <Icon icon="ri:add-line" />
                  </span>
                </template>
              </Button>
            </Tooltip>
          </template>
          <Draggable
            v-model="widget.widgets"
            animation="200"
            class="divide-y divide-gray-200 rounded-lg bg-white shadow"
            item-key="id"
            @end="onDragEnd"
            @start="state.dragging = true"
          >
            <template #item="{ element }">
              <div
                :class="{ 'not-draggable': !state.enabled }"
                class="flex cursor-pointer items-center justify-between px-4 py-3 transition duration-200 hover:bg-gray-100"
                style="cursor: move"
              >
                <span class="font-medium text-gray-700">
                  {{ element.title }}
                </span>
                <div class="flex space-x-3">
                  <span
                    v-if="element.public_widget_id"
                    class="anticon mr-3 text-green-500 transition duration-200 hover:text-green-700"
                  >
                    <Tooltip title="全局组件">
                      <Icon icon="ri:focus-2-fill" />
                    </Tooltip>
                  </span>
                  <Tooltip title="组件设置">
                    <Button
                      type="link"
                      @click="openWidgetsSettingModal(key, element)"
                    >
                      <template #icon>
                        <span class="anticon">
                          <Icon icon="ri:settings-5-line" />
                        </span>
                      </template>
                    </Button>
                  </Tooltip>
                  <Tooltip title="删除组件">
                    <Popconfirm
                      cancel-text="否"
                      ok-text="是"
                      title="确认删除？"
                      @confirm="handleDelete(element, key)"
                    >
                      <Button danger type="link">
                        <template #icon>
                          <span class="anticon">
                            <Icon icon="ri:delete-bin-line" />
                          </span>
                        </template>
                      </Button>
                    </Popconfirm>
                  </Tooltip>
                </div>
              </div>
            </template>
          </Draggable>
        </Card>
      </TabPane>
      <TabPane v-if="state.has_config" key="2" tab="设置">
        <Form />
      </TabPane>
      <TabPane v-if="state.has_public_config" key="3" tab="全局设置">
        <Form />
      </TabPane>
    </Tabs>
  </Drawer>
</template>

<style lang="scss" scoped>
.not-draggable {
  cursor: no-drop;
}
</style>
